package com.css.openapi.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.css.common.core.constant.ReturnCode;
import com.css.common.core.exception.ServiceException;
import com.css.common.core.session.SessionManager;
import com.css.common.core.session.SessionUtils;
import com.css.common.core.utils.BaseUtil;
import com.css.openapi.BO.*;
import com.css.openapi.BO.lypt.ShbdResponse;
import com.css.openapi.BO.lypt.ShbdztQueryRepsonse;
import com.css.openapi.entity.QyYwlx;
import com.css.openapi.feign.ZfjkpPtCommonClient;
import com.css.openapi.mapper.QyYwlxMapper;
import com.css.openapi.service.IQyYwlxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 企业业务类型明细 服务实现类
 * </p>
 *
 * @author qinxb
 * @since 2025-01-20 10:18:38
 */
@Slf4j
@Service
public class QyYwlxServiceImpl extends ServiceImpl<QyYwlxMapper, QyYwlx> implements IQyYwlxService {

    @Resource
    private ZfjkpPtCommonClient zfjkpPtCommonClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ShbdBO bingYwlx(ShbdReq shbdReq) {
        chekcReq(shbdReq);
        String appid = SessionManager.get().getAppid();
        //调用支付即开票平台
        ShbdResponse shbdRep= zfjkpPtCommonClient.shbdsq(shbdReq);
        if(!Objects.equals(shbdRep.getCode(), "0"))throw new ServiceException(shbdRep.getMsg());
        //返回数据保存
        this.saveOrUpdate(new QyYwlx()
                .setShbdbh(shbdRep.getShbdbh())
                .setAppid(appid)
                .setYwlxDm(shbdReq.getYwlx())
                .setBdzt(null)
                .setLxrmc(shbdReq.getLxrmc())
                .setLxrsjh(shbdReq.getLxrsjh())
                .setLxrsfzjhm(shbdReq.getLxrsfzjhm())
                .setShsh(shbdReq.getShsh())
                .setShmc(shbdReq.getShmc())
                .setCjr(appid)
                .setCjsj(LocalDateTime.now()));
        //组装返回参数
        ShbdBO bo=new ShbdBO();
        bo.setShbdbh(shbdRep.getShbdbh());
        bo.setSqjg(shbdRep.getSqjg());
        bo.setShdjxx(shbdRep.getShdjxx());
        return bo;
    }

    @Override
    public Map<String, String> queryShbdzt(ShbdztQueryRequest request) {
        ShbdztQueryRepsonse queryRepsonse= zfjkpPtCommonClient.queryShbdzt(request);
        if(!Objects.equals("0",queryRepsonse.getCode()))throw new ServiceException(queryRepsonse.getMsg());
        QyYwlx qyYwlx=new QyYwlx();
        qyYwlx.setShbdbh(request.getShbdbh());
        qyYwlx.setBdzt(queryRepsonse.getBdzt());
        this.updateById(qyYwlx);
        Map<String, String> rep=new HashMap<>();
        rep.put("shbdbh",request.getShbdbh());
        rep.put("bdzt",queryRepsonse.getBdzt());
        rep.put("sfyewmyz",queryRepsonse.getSfyewmyz());
        return rep;
    }

    @Override
    public void unBindYwlx(ShbdztQueryRequest request) {
        ReturnCode result= zfjkpPtCommonClient.unBindYwlx(request);
        if(!Objects.equals("0",result.getCode()))throw new ServiceException(result.getMsg());
        List<QyYwlx> qyYwlxes=null;
        if(!BaseUtil.isNull(request.getShbdbh())&&BaseUtil.isNull(request.getYwlx())){
            qyYwlxes=this.lambdaQuery().eq(QyYwlx::getShbdbh,request.getShbdbh()).eq(QyYwlx::getScbj,"0").eq(QyYwlx::getBdzt,"00").list();
        }else {
            qyYwlxes=this.lambdaQuery().eq(QyYwlx::getShbdbh,request.getShbdbh()).eq(QyYwlx::getYwlxDm,request.getYwlx()).eq(QyYwlx::getScbj,"0").eq(QyYwlx::getBdzt,"00").list();
        }
        if(BaseUtil.isNull(qyYwlxes))throw new ServiceException("未查询到已绑定信息");
        for (QyYwlx qyYwlx : qyYwlxes) {
            boolean is=this.lambdaUpdate().eq(QyYwlx::getShbdbh,qyYwlx.getShbdbh())
                    .eq(QyYwlx::getYwlxDm, qyYwlx.getYwlxDm()).set(QyYwlx::getBdzt,"05")
                    .set(QyYwlx::getXgr,SessionUtils.getAppid()).set(QyYwlx::getXgsj,LocalDateTime.now()).update();
            log.info("商户解绑编号:{}，业务类型：{}，update:{}",request.getShbdbh(),request.getYwlx(),is);
        }
    }

    /**
     * 校验是否绑定
     * @param shbdReq 入参
     * @return 返回
     */
    private ShbdBO checkData(Optional<QyYwlx> optional,ShbdReq shbdReq) {
        ShbdBO shbdBO = new ShbdBO();
//        String ywlxMc = YwlxEnum.getMc(shbdReq.getYwlx());
//        if (Objects.isNull(ywlxMc)) throw new ServiceException("业务类型:" + shbdReq.getYwlx() + ",不存在");
//        //校验业务类型是否已绑定
//        if (optional.isPresent()) {
//            QyYwlx qyYwlx = optional.get();
//            String lxrmc = shbdReq.getLxrmc();
//            String lxrsjh = shbdReq.getLxrsjh();
//            shbdBO.setShbdbh(qyYwlx.getShbdbh());
//            if("00".equals(qyYwlx.getBdzt())){
//                shbdBO.setShbdbh(qyYwlx.getShbdbh());
//                shbdBO.setSqjg("04");//已绑定成功,无需再次申请
//                return shbdBO;
//            }
//            if (!Objects.equals(lxrmc, qyYwlx.getLxrmc()) || !Objects.equals(lxrsjh, shbdReq.getLxrsjh())) {
//                shbdBO.setSqjg("00");//申请失败 企业对于的业务类型已绑定但联系人信息不一致
//            }
//            return shbdBO;
//        }
        return shbdBO;
    }

    private void chekcReq(ShbdReq shbdReq){
        if (!BaseUtil.isValidPhoneNumber(shbdReq.getLxrsjh())) {
            throw new ServiceException("手机号格式不正确");
        }
        if(shbdReq.getShsh().length()<15||shbdReq.getShsh().length()>20){
            throw new ServiceException("商户税号长度应15至20位");
        }
        if(!shbdReq.getShsh().trim().matches("[a-zA-Z0-9]+")){
            throw new ServiceException("商户税号应由数字,字母组成");
        }
    }



}
